#include <iostream>
#include <unistd.h>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage: ./client ip port[1024+]";
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t port = atoi(argv[2]);

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    server.sin_port = htons(port);

    while (true)
    {
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            std::cout << "socket error, errno:" << errno << ", errerstr:" << strerror(errno) << std::endl;
            exit(0);
        }
        std::cout << "socket over..." << std::endl;
        if (connect(sockfd, (struct sockaddr *)&server, sizeof(server)) < 0)
        {
            std::cout << "connect error, errno:" << errno << ", errerstr:" << strerror(errno) << std::endl;
            sleep(2);
            continue;
        }
        std::cout << "connect over..." << std::endl;
        while (true)
        {
            std::string say;
            std::getline(std::cin, say);
            if (write(sockfd, say.c_str(), say.size()) < 0)
            {
                std::cout << "write error, errno:" << errno << ", errerstr:" << strerror(errno) << std::endl;
                break;
            }
            char buffer[1024];
            int n = read(sockfd, buffer, sizeof(buffer));
            if (n <= 0)
            {
                std::cout << "read error, errno:" << errno << ", errerstr:" << strerror(errno) << std::endl;
                break;
            }
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
        std::cout << "yyyyyyyyy" << std::endl;
    }

    return 0;
}